//
//  OrdiniViewController.m
//  iTeVe
//
//  Created by Pedro Gonzalez on 25/02/14.
//  Copyright (c) 2014 SISI Software. All rights reserved.
//

#import "OrdiniViewController.h"
#import "FMDBDataAccess.h"
#import "Testa.h"
#import "TestaVisualizzazione.h"
#import "OrdineCell.h"

@interface OrdiniViewController ()

@end

@implementation OrdiniViewController

bool primavolta;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = NSLocalizedString(@"TABELLA_ORDINI", @"Tabella ordini...");
    self.navigationItem.prompt = @"iTeVe";
    
    [self populateOrdini:@""];
    primavolta = YES;

//    [super setEditing:YES animated:YES]; // per mettere in modo edit -  e far comparire i pulsanti di cancellazione a sinistra. (editingStyleForRowAtIndexPath)
}


-(void) populateOrdini:(NSString *)filtro
{
    ordini = [[NSMutableArray alloc] init];
    
    FMDBDataAccess *db = [[FMDBDataAccess alloc] init];
    
    ordini = [db getTestaForVisualizzazione:@""];
}


- (void) viewDidAppear:(BOOL)animated
{
    if (primavolta) {
        [super viewDidAppear:animated];
        
        [self visualizzoUltimo];
        
        /*
        if (self.tableView.contentSize.height > self.tableView.frame.size.height)
        {
            CGPoint offset = CGPointMake(0, self.tableView.contentSize.height -     self.tableView.frame.size.height);
            [self.tableView setContentOffset:offset animated:YES];
        }
         */
        primavolta = NO;
    }
}


- (void) visualizzoUltimo
{
    if (self.tableView.contentSize.height > self.tableView.frame.size.height)
    {
        CGPoint offset = CGPointMake(0, self.tableView.contentSize.height -     self.tableView.frame.size.height);
        [self.tableView setContentOffset:offset animated:YES];
    }

    
}

/*
-(void)viewWillAppear:(BOOL)animated {
 
    [self.tableView reloadData];
    NSIndexPath* ip = [NSIndexPath indexPathForRow:[self.tableView numberOfRowsInSection:0] - 1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:NO];

}
*/

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [ordini count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"OrdineCell";
    
    OrdineCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    TestaVisualizzazione *ordine = [ordini objectAtIndex:[indexPath row]];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd/MM/yyyy"];
    cell.dataMovimento.text = [formatter stringFromDate:ordine.dataora];
    cell.tipoMovimento.text = [[ordine.codtipmov stringByAppendingString:@" - "] stringByAppendingString:ordine.descmov];
    cell.clienteMovimento.text = ordine.ragionesociale;
    
    return cell;
}


/*
// The editing style for a row is the kind of button displayed to the left of the cell when in editing mode.
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    // No editing style if not editing or the index path is nil.
    
    // Determine the editing style based on whether the cell is a placeholder for adding content or already
    // existing content. Existing content can be deleted.
    if (indexPath.row == ([ordini count])) {
		return UITableViewCellEditingStyleInsert;
	} else {
		return UITableViewCellEditingStyleDelete;
	}
    return UITableViewCellEditingStyleNone;
}
*/



- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // cancello ordine
//    [Utility showAlert:@"Info" message:@"Non si possono cancellare gli ordini... per adesso" ];
    
    FMDBDataAccess *db = [[FMDBDataAccess alloc] init];
    Testa *ordine = [ordini objectAtIndex:[indexPath row]];
    
    [db removeTesta:ordine];
    [self populateOrdini:@""];
    [self.tableView reloadData];
//    [self dismissViewControllerAnimated:YES completion:nil];
    
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"segueOrdineEdit"]) {
        
        Testa *ordine = [ordini objectAtIndex:[self.tableView indexPathForCell:sender].row];

        FMDBDataAccess *db = [[FMDBDataAccess alloc] init];
        Testa *testa = [db getTestaxId:ordine.id];
        
        testa.nuovo = [NSNumber numberWithBool:NO];
        UINavigationController *navigationController = segue.destinationViewController;
        OrdineDVStaticViewController *destViewController = [navigationController viewControllers][0];
        //Cliente *cliente = [db getClienteXid:ordine.idcliente];
        //testa.datiCliente = cliente;
        //testa.idcliente = cliente.idcliente;
        //destViewController.modelCliente = cliente;
        destViewController.modelTesta = testa;
        destViewController.delegate = self;
    }
    else if ([segue.identifier isEqualToString:@"segueOrdineAdd"]) {

        UINavigationController *navigationController = segue.destinationViewController;
        OrdineDVStaticViewController *destViewController = [navigationController viewControllers][0];
        Testa *testa = [[Testa alloc] init];
        testa.nuovo = [NSNumber numberWithBool:YES];
        destViewController.modelTesta = testa;
        destViewController.delegate = self;

    }
    
}


-(void) ordineDVStaticViewControllerDidCancel:(OrdineDVStaticViewController *)controller
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void) ordineDVStaticViewControllerDidSave:(OrdineDVStaticViewController *)controller
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void) ordineDVStaticViewController:(OrdineDVStaticViewController *)controller didEditOrdine:(Testa *)ordine
{
    FMDBDataAccess *db = [[FMDBDataAccess alloc] init];
    
    [db updateTesta:ordine];


//    NSString *text = searchClienti.text;
//    if(text.length > 0){
//        [self populateOrdini:text];
//    } else {
        [self populateOrdini:@""];
//    }
    
    [self.tableView reloadData];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}



-(void) ordineDVStaticViewController:(OrdineDVStaticViewController *)controller didAddOrdine:(Testa *)ordine
{
    FMDBDataAccess *db = [[FMDBDataAccess alloc] init];
    
    [db insertTesta:ordine];
  
        [self populateOrdini:@""];

//    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[ordini count] - 1 inSection:0];
//    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView reloadData];
    [self visualizzoUltimo];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}






@end
